import { defineStore } from "pinia";
import { store } from "../utils";
import { readonly, ref } from "vue";

export const useLunchStore = defineStore("pure-lunch", () => {
  // 是否初始化
  const hasInit = ref(false);
  // 是否在线
  const isOnline = ref<boolean>(navigator.onLine);
  // 是否激活
  const isWindowActive = ref<boolean>(false);

  const updateOnlineStatus = () => {
    isOnline.value = navigator.onLine;
  };

  // 初始化
  const init = () => {
    if (!hasInit.value) {
      hasInit.value = true;
      // 监听浏览器原生的 online/offline 事件，实时更新
      window.addEventListener("online", updateOnlineStatus);
      window.addEventListener("offline", updateOnlineStatus);

      // 定时检测，防止事件丢失
      setInterval(updateOnlineStatus, 5000);
      const updateActiveStatus = () => {
        isWindowActive.value = document.visibilityState !== "hidden";
      };

      // 监听 visibilitychange 事件，实时更新窗口激活状态
      document.addEventListener("visibilitychange", updateActiveStatus);

      // 初始化时立即设置一次
      updateActiveStatus();
    }
  };

  return {
    isOnline: readonly(isOnline),
    isWindowActive: readonly(isWindowActive),
    init
  };
});

export function useLunchStoreHook() {
  return useLunchStore(store);
}
